A map from each vertex to its neighbors.
- An adjacency list is essentially a dictionary or map where each key is a vertex, and the value is a list or set of its adjacent vertices.
- This structure is highly efficient for sparse graphs (graphs with few edges) because it only stores the connections that actually exist.
- For undirected graphs, the relationship is symmetric. If vertex B is in A's neighbor list, then A must be in B's list. This symmetry must be maintained.
Python Implementation
# Undirected adjacency list using sets for O(1) membership
V = ["A", "B", "C", "D"]
adj = {v: set() for v in V}
edges = [("A", "B"), ("A", "C"), ("B", "D")]
for u, v in edges:
adj[u].add(v) # Add v to u's neighbors
adj[v].add(u) # Maintain symmetry for undirected graphs
# Result: {'A':{'B','C'}, 'B':{'A','D'}, 'C':{'A'}, 'D':{'B'}}